package com.party.core.service.mall.biz;

import com.google.common.base.Function;
import com.google.common.collect.Lists;
import com.party.common.utils.LangUtils;
import com.party.common.utils.StringUtils;
import com.party.core.model.mall.MallCategory;
import com.party.core.model.mall.MallCategoryBrand;
import com.party.core.model.mall.MallCategorySpec;
import com.party.core.model.mall.MallGoodsCategory;
import com.party.core.service.mall.IMallCategoryBrandService;
import com.party.core.service.mall.IMallCategoryService;
import com.party.core.service.mall.IMallCategorySpecService;
import com.party.core.service.mall.IMallGoodsCategoryService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.List;

/**
 * 分类业务处理
 * Created by yifeng
 *
 * @date 2018/3/28 0028
 * @time 下午 16:10
 */
@Service
public class GoodsCategoryBizService {
    @Autowired
    private IMallGoodsCategoryService mallGoodsCategoryService;
    @Autowired
    private IMallCategoryService mallCategoryService;
    @Autowired
    private IMallCategoryBrandService mallCategoryBrandService;
    @Autowired
    private IMallCategorySpecService mallCategorySpecService;

    Logger logger = LoggerFactory.getLogger(getClass());

    /**
     * 保存商品分类
     *
     * @param goodsId      商品id
     * @param categoryList 分类集合
     */
    public void saveCategoryBiz(String goodsId, String categoryList) {
        if (StringUtils.isNotEmpty(categoryList)) {
            for (String categoryId : categoryList.split(",")) {
                MallGoodsCategory category = mallGoodsCategoryService.getUnique(new MallGoodsCategory(goodsId, categoryId));
                if (category == null) {
                    category = new MallGoodsCategory(goodsId, categoryId);
                    mallGoodsCategoryService.insert(category);
                }
            }
        }
        List<MallGoodsCategory> oldPicList = mallGoodsCategoryService.findByGoodsId(goodsId);
        List<String> oldCategories = LangUtils.transform(oldPicList, input -> input.getCategoryId());
        if (StringUtils.isNotEmpty(categoryList)) {
            List<String> newCategories = Arrays.asList(categoryList.split(","));
            oldCategories.removeAll(newCategories);
        }

        for (String oldPic : oldCategories) {
            mallGoodsCategoryService.deleteByUnique(new MallGoodsCategory(goodsId, oldPic));
        }
    }

    /**
     * 复制分类
     *
     * @param oldGoodsId 旧的商品
     * @param newGoodsId 新的商品
     */
    public void copyCategory(String oldGoodsId, String newGoodsId) {
        StringBuilder sb = new StringBuilder();
        List<MallGoodsCategory> goodsCategories = mallGoodsCategoryService.list(new MallGoodsCategory(oldGoodsId, ""));
        for (MallGoodsCategory category : goodsCategories) {
            category.setGoodsId(newGoodsId);
            category.setId(null);
            mallGoodsCategoryService.insert(category);

            sb.append(category.getCategoryId() + ",");
        }

        try {
            if (StringUtils.isNotEmpty(sb.toString())) {
                String str = sb.toString();
                str = str.substring(0, str.length() - 1);
                this.updateGoodsNum(true, newGoodsId, str);
            }
        } catch (Exception e) {
            logger.error("处理品牌的商品数异常", e);
        }
    }

    /**
     * 更新商品数量
     *
     * @param newCateIdStr 新的分类
     * @param goodsId      商品id
     */
    public void updateGoodsNum(boolean isNew, String goodsId, String newCateIdStr) {

        List<String> newCategoryIds = Lists.newArrayList();
        if (StringUtils.isNotEmpty(newCateIdStr)) {
            newCategoryIds.addAll(Arrays.asList(newCateIdStr.split(",")));
        }

        if (!isNew) {
            List<MallGoodsCategory> oldCategories = mallGoodsCategoryService.findByGoodsId(goodsId);
            List<String> oldCategoryIds = LangUtils.transform(oldCategories, new Function<MallGoodsCategory, String>() {
                @Override
                public String apply(MallGoodsCategory input) {
                    return input.getCategoryId();
                }
            });
            String oldCateIdStr = oldCategoryIds.toString().replaceAll("\\[", "").replaceAll("\\]", "");
            oldCategoryIds.removeAll(newCategoryIds);

            for (String categoryId : oldCategoryIds) {
                MallCategory mallCategory = mallCategoryService.get(categoryId);
                mallCategory.setGoodsNum(mallCategory.getGoodsNum() - 1);
                mallCategoryService.update(mallCategory);
            }


            if (!(oldCategories.size() > 0 && oldCategoryIds.size() == 0)) {
                List<String> result = Lists.newArrayList();
                for (String newIds : newCategoryIds) {
                    for (String oldIds : oldCateIdStr.split(",")) {
                        if (newIds.equals(oldIds.trim())) {
                            result.add(oldIds.trim());
                        }
                    }
                }
                newCategoryIds.removeAll(result);
                for (String categoryId : newCategoryIds) {
                    MallCategory mallCategory = mallCategoryService.get(categoryId);
                    mallCategory.setGoodsNum(mallCategory.getGoodsNum() + 1);
                    mallCategoryService.update(mallCategory);
                }
            }
        } else {
            for (String categoryId : newCategoryIds) {
                MallCategory mallCategory = mallCategoryService.get(categoryId);
                mallCategory.setGoodsNum(mallCategory.getGoodsNum() + 1);
                mallCategoryService.update(mallCategory);
            }
        }
    }

    /**
     * 保存分类和品牌的关系
     *
     * @param categoryIds 新的分类
     * @param brandId     品牌id
     */
    public void saveCategoryBrand(String categoryIds, String brandId) {
        List<String> newCategoryIds = Lists.newArrayList();
        if (StringUtils.isNotEmpty(categoryIds)) {
            newCategoryIds.addAll(Arrays.asList(categoryIds.split(",")));
        }
        for (String categoryId : newCategoryIds) {
            MallCategoryBrand query = new MallCategoryBrand(categoryId, brandId);
            MallCategoryBrand categoryBrand = mallCategoryBrandService.getUnique(query);
            if (categoryBrand == null) {
                mallCategoryBrandService.insert(query);
            }
        }
    }

    /**
     * 根据商品id删除商品分类
     *
     * @param goodsId 商品id
     */
    public void deleteByGoods(String goodsId) {
        List<MallGoodsCategory> goodsCategories = mallGoodsCategoryService.findByGoodsId(goodsId);
        for (MallGoodsCategory goodsCategory : goodsCategories) {
            if (StringUtils.isNotEmpty(goodsCategory.getCategoryId())) {
                MallCategory mallCategory = mallCategoryService.get(goodsCategory.getCategoryId());
                if (mallCategory != null) {
                    mallCategory.setGoodsNum(mallCategory.getGoodsNum() - 1);
                    mallCategoryService.update(mallCategory);
                }
            }
            mallGoodsCategoryService.delete(goodsCategory.getId());
        }
    }

    /**
     * 删除验证
     *
     * @param categoryId 分类id
     * @return
     */
    public boolean checkDelete(String categoryId) {
        boolean deleteFlag = true;
        List<MallGoodsCategory> goodsCategories = mallGoodsCategoryService.findByCategoryId(categoryId);
        if (goodsCategories.size() == 0) {
            List<MallCategoryBrand> categoryBrands = mallCategoryBrandService.findByCategoryId(categoryId);
            if (categoryBrands.size() == 0) {
                List<MallCategorySpec> categorySpecs = mallCategorySpecService.findByCategoryId(categoryId);
                if (categorySpecs.size() != 0) {
                    deleteFlag = false;
                }
            } else {
                deleteFlag = false;
            }
        } else {
            deleteFlag = false;
        }
        return deleteFlag;
    }
}
